<template>
  <div class="container">
    <a-spin size="large" :tip="tip">
      <div class="container"></div>
    </a-spin>
  </div>
</template>
<script lang="ts" setup>
import { useRoute } from "vue-router";
import LocalCache from "@/utils/cache";
import {
  requestSysInfo,
  accountLoginRequest,
  getTokenAddOrgCode,
  queryBaseconfig,
  getYearList,
  getAllGrade,
  queryTeacher,
  getClassIdMap,
} from "@/service/modules/public/public";
// import { useStore } from "vuex";s
import router from "@/router";
import { Toast } from "vant";
import { APPID } from "@/service/request/config";
import CryptoJS from "crypto-js";
import qs from "qs";
const md5 = require("md5");
const tip = "加载中...";
const route = useRoute();
const default_actk =
  "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI0NjcyODI2ODE1MTY0NzAyNzMiLCJpYXQiOjE3MTU1NjgxMjQsImFjY291bnRObyI6ImxwNWJnIiwibG9naW5EZXZpY2UiOiJtaW5pYXBwIiwiZXhwIjoxNzE1NjU0NTI0fQ.j-ufAljylWI8Ex7C-ebQfp682UW6CbB_PvY3ZcCfeSSHJHWmwYJoFDM5--rL7o9eJiUODZj64aafy_-J3obwnhzV2p1HLuHVaPsiGhcTdSdK-r5LoTLLiOdKZUUcf3e1ZM4ITngIw0Q55Jv7uWwK2x_TdSFlLa3nfqQDFZg9QWU";
getAppToken();
// 获取orgCode与token
/**
 * @desc: 初始化
 * @author: went
 */
async function initIdentity(_token: String, orgCode: String, personId: String) {
  const query = qs.parse(decodeURIComponent(route.fullPath.split("?")[1]));
  LocalCache.setCache("eClassId", query?.eClassId || "");
  LocalCache.setCache("accessToken", query?.accessToken || default_actk);
  const params = {
    accessToken: query?.accessToken || default_actk,
    appId: APPID,
    studentId: query?.studentId || "",
    orgCode,
    token: _token,
    personId,
  };
  const { code, token } = await accountLoginRequest(params);
  if (code === 0) {
    LocalCache.setCache("token", token);
    await baseconfig();
    getSysInfo();
  }
}

/**`
 * @desc: 获取用户信息
 * @author: went
 */
async function getSysInfo() {
  const { code, data } = await requestSysInfo();
  const sRes = await getClassIdMap({
    token: LocalCache.getCache("orgToken"),
    orgCode: LocalCache.getCache("orgCode"),
  });
  let curClassId = "";
  if (sRes.code === "200") {
    let eClassId = LocalCache.getCache("eClassId");
    (sRes?.data || []).some((item) => {
      if (item.thirdClassId === eClassId) {
        curClassId = item.classId;
        LocalCache.setCache("curClassId", curClassId || "");
        return true;
      }
    });
  }
  console.log(curClassId)
  if (code === 0) {
    queryTeacher({
      pageNum: 1,
      pageSize: 999999,
      orgCode: LocalCache.getCache("orgCode")
    }).then((res: any) => {
      // 判断是否是巡查角色
      let xcRole = (res?.rows || []).filter(
        (item: any) => item.teacherId === data.personId
      );

      console.log(xcRole)

      // JSBJZW_1 为班主任
      let monitorRole = false;
      let monitorList = [];
      if (data?.jobList && Array.isArray(data.jobList)) {
        // 得到是否是班主任
        monitorRole = (data?.jobList || []).some(
          (item: any) =>
            item.jobId === "JSBJZW_1" && item.classId === curClassId
        );
        // 获取班主任对象数据
        monitorList = (data?.jobList || []).filter(
          (item: any) => item.classId === curClassId
        );
        // 如果班主任列表为空，则获取班主任列表
        if (monitorList.length === 0) {
          monitorList = (data?.jobList || []).filter(
            (item: any) => item.jobId === "JSBJZW_1"
          );
        }
      }

      console.log(monitorRole)

      LocalCache.setSession("userInfo", {
        ...data,
        isAdmin: xcRole.length > 0,
      });

      // 跳转判断
      if (xcRole.length > 0) {
        router.replace("/home");
      } else if (monitorRole) {
        const gradeFlatList = LocalCache.getSession("gradeFlatList");
        const gradeData = gradeFlatList.filter(
          (item) => item?.className === monitorList[0]?.className
        );
        router.replace({
          path: "/classEvaluation",
          query: {
            grade: gradeData[0].gradeName,
            classes: monitorList[0]?.className,
            gradeId: gradeData[0].gradeId,
            classId: gradeData[0]?.classId
          },
        });
      } else {
        router.replace("/empty");
      }
    });
  } else {
    Toast.success(data?.message);
  }
}

/**
 * 计算appToken
 */
async function getAppToken() {
  const query = qs.parse(decodeURIComponent(route.fullPath.split("?")[1]));
  const { accessToken = default_actk } = query;
  let appId = "JF-ISWCC-WEB";
  let appAuthorizeCode = "00003A32774441869306A38D38CCDA41";
  const timeStamp = new Date().getTime();
  const key = md5(timeStamp + "").slice(8, 24);
  const appToken = encrypt(appId + appAuthorizeCode + timeStamp, key);
  const {
    code,
    data: { token, orgCode, personId },
  } = await getTokenAddOrgCode(appToken, timeStamp, accessToken);
  if (code === "200") {
    LocalCache.setCache("orgToken", token);
    LocalCache.setCache("orgCode", orgCode);
    initIdentity(token, orgCode, personId);
  }
}

/**
 * 加密算法
 */
function encrypt(word: string, keyStr: string) {
  if (word && keyStr) {
    var key = CryptoJS.enc.Utf8.parse(keyStr); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.ciphertext.toString();
  } else {
    return false;
  }
}

// 获取配置
async function baseconfig() {
  const resList = await Promise.all([
    getYearList(),
    queryBaseconfig(),
    getAllGrade(),
  ]);

  // 获取学年学期列表
  if (resList[0].code === 0) {
    // 学年选项列表
    LocalCache.setSession("yearSemAddVacationList", resList[0].data);
  }

  // 获取配置信息
  if (resList[1].code === 0) {
    resList[1].data.forEach((item: { configName: string }) => {
      if (item.configName === "EVALUATE_PERIOD") {
        LocalCache.setSession("baseConfig", item);
      }
    });
  }

  // 获取年级列表
  if (resList[2].code === 0) {
    LocalCache.setSession("gradeList", resList[2].rows);

    let gradeAndClassFlat;

    const gradeAndClass = resList[2].rows.map((item: any) => {
      if (item.children.length === 0) {
        return {
          gradeName: item.unitName,
          gradeId: item.unitId,
        };
      }

      return item.children.map((subItem: any) => {
        const result: any = {};
        result.gradeName = item.unitName;
        result.gradeId = item.unitId;
        result.className = subItem.unitName;
        result.classId = subItem.unitId;
        return result;
      });
    });

    gradeAndClassFlat = gradeAndClass.flat();

    LocalCache.setSession("gradeFlatList", gradeAndClassFlat);
  }

  return true;
}
</script>

<style scoped lang="less">
.container {
  width: 100%;
  height: 100vh;
}
</style>
